#! /usr/bin/env python
# -*- coding:utf-8 -*-

import requests
from lxml import etree
import datetime
import re
import uuid
import sys
import logging
import time
import json
import os

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# 西安工程大学教务处IP
school_base_url = "http://202.200.206.54/"
headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36'
}

# 拿Location字段，如果后期加入Cookie可避免Expection
session = requests.Session()
login_page = session.get(url=school_base_url, headers=headers, allow_redirects=False)
location_url = login_page.headers.get("Location")
have_location_url = "http://202.200.206.54" + location_url

# 请求带的信息
request_info = {}
response = {
    'error' : '0',
    'msg' : '验证码保存成功',
    'data' : {},
}


def getCodeimg(file_path):
    #logger.info("The json params is: %s" % file_path)
    if not os.path.exists(file_path):
        response['error'] = '1'
        response['msg'] = '目录不存在'
        return json.dumps(response)
    # 拿验证码图片
    new_page_text = session.get(url=have_location_url, headers=headers).text
    tree = etree.HTML(new_page_text)
    # 随机字符
    location_word = location_url.split('/')[1]
    code_img_src = 'http://202.200.206.54/' + location_word + '/' + tree.xpath('//*[@id="icode"]/@src')[0]
    img_data = requests.get(url=code_img_src, headers=headers).content
    # 验证码文件名：毫秒级时间戳
    file_name = str(round(time.time() * 1000)) + '.jpg'
    file_address = os.path.join(file_path, file_name)
    with open(file_address, 'wb') as fp:
        fp.write(img_data)
    if os.path.exists(file_address):
        response['data']['location_url'] = location_url
        response['data']['have_location_url'] = have_location_url
        response['data']['file_address'] = file_address
        #response['data']['session'] = session
    else:
        response['error'] = '1'
        response['msg'] = '验证码保存失败'
    return json.dumps(response)


def main():
    file_path = sys.argv[1]
    resp = getCodeimg(file_path)
    print(resp)
    return resp

if __name__ == '__main__':
    main()





